<?php
namespace App\Http\Controllers;
use App\Exceptions\ValidateException;
use App\Repository\Contracts\MemberRechargeInterface;
use App\Support\Helper\CommonHelper;
use Illuminate\Http\Request;
use Auth;

/**
 * @Author:: HuangYin
 * @DateTime: 2017-01-17 19:52
 *
 * @Description: 会员充值
 */
class MemberRechargeController extends Controller
{
    /**
     * @var Request
     */
    protected $request;

    /**
     * @var MemberRechargeInterface
     */
    protected $memberRecharge;

    protected $uid;

    protected $storeId;

    /**
     * MemberRechargeController constructor.
     * @param Request $request
     * @param MemberRechargeInterface $memberRecharge
     */
    public function __construct(Request $request, MemberRechargeInterface $memberRecharge)
    {
        $this->request = $request;

        $this->memberRecharge = $memberRecharge;

        $this->uid = CommonHelper::getToken(Auth::user())['uid'];

        $this->storeId = CommonHelper::getToken(Auth::user())['storeId'];
    }

    /**
     * @return \Illuminate\Http\JsonResponse
     */
    public function index()
    {
        $limit = $this->request->input('limit', 15);
        $page = $this->request->input('page', 1);
        $uid = $this->request->input('uid', null);
        //Search Map
        $searchMap = $this->searchMap([
            ['uid', $uid, '=']
        ]);
        $list = $this->memberRecharge->lists($limit, $page, $searchMap);

        return $this->success($list);
    }

    /**
     * @param $uid
     * @return \Illuminate\Http\JsonResponse
     */
    public function detail($uid)
    {
        $detail = $this->memberRecharge->detail($uid);

        return $this->success($detail);
    }

    /**
     * @return \Illuminate\Http\JsonResponse
     */
    public function created()
    {
        try {
            $data = $this->request->only(['uid', 'money', 'memo']);
            $data['store_id'] = $this->storeId;
            $data['admin_id'] = $this->uid;
            $id = $this->memberRecharge->created($data);

            return $this->success($id);
        } catch (ValidateException $e) {

            return $this->validateError($e);
        }
    }

    /**
     * Update
     *
     * @param $uid
     * @return \Illuminate\Http\JsonResponse
     */
    public function updated($uid)
    {
        try {
            $data = $this->request->only(['money', 'memo']);
            $data['store_id'] = $this->storeId;
            $data['admin_id'] = $this->uid;
            $result = $this->memberRecharge->updated($uid, $data);

            return $this->success($result);
        } catch (ValidateException $e) {

            return $this->validateError($e);
        }
    }
}